import axios from 'axios'
import { Loading } from 'element-ui';
import router from '../router/'
import {
    Message
} from 'element-ui'

const service = axios.create({
    baseURL: 'https://bjsf.bjsky.top/',
    // baseURL: 'http://bjsf.bjsky.top/',
    timeout: 20000
});

service.defaults.headers.post['Content-Type'] = 'content-type:application/json'; // 配置请求头

//添加请求拦截器
service.interceptors.request.use(
    config => {

        Loading.service({
            lock: true,
            text: '加载中.....',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
        });
        if (sessionStorage.getItem('token')) {
            config.headers['auth-token'] = sessionStorage.getItem('token') ? sessionStorage.getItem('token') : ''
        }
        if (config.data == undefined) {
            config.data = {}
        }
        if (config.method === 'post') {
            config.data.adminId = sessionStorage.getItem('user_id')
            config.data.timeStamp = sessionStorage.getItem('timeStamp')
            if (config.data.page > 0) {
                config.data.page = config.data.page - 1
            }
        }
        return config;

    },
    error => {
        return Promise.reject(error);
    });
//添加响应拦截器
service.interceptors.response.use(
    response => {

        if (response.data.code != 200) {
            if (response.data.code == '401' || response.data.code == '-9') {
                Message.error('请重新登录')
                setTimeout(() => { // 返回请先登录的状态码 回跳登录
                    sessionStorage.removeItem('token')
                    sessionStorage.removeItem('user_id')
                    sessionStorage.removeItem('timeStamp')

                    router.options.isAddDynamicMenuRoutes = false
                    router.push({
                        name: 'login'
                    })
                }, 600)
            } else {
                Message.error(response.data.msg)
            }


        }

        Loading.service().close();
        return response.data;

    },
    error => {
        if (!error.response) {
            Loading.service().close();
            Message.warning('请求超时')
            return
        }
        Loading.service().close();
        if (error.response.status) {
            switch (error.response.status) {
                case 404:
                    Message.warning('服务器被外星人抓走了~')
                    break
                // 其他错误，直接抛出错误提示
                default:
                    Message.warning('服务器发生意外错误，错误code：' + error.response.status)
            }
        }
        return Promise.reject(error)
    });
export default service;
